# -*- coding: utf-8 -*-

class SeparateOrderController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :privilege_filter

  #显示新增拆分订单页面
  def newSeparate
    
  end

  #显示编辑拆分订单页面
  def editSeparate

  end

  #显示审批拆分订单页面
  def auditSeparateOrder
    
  end
  
  #拆分列表页面
  def separateOrderList
    
  end

  #显示拆分页面列表
  def separateOrderAuditList
    
  end

  #得到所有的拆分单
  def getAllSeparateOrders
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = ''

    if params[:order_number].to_s != ''
      conditionsStr = 'seq_number in (:order_number)'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:warehouse_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'warehouse_id = :warehouse_id'
      else
        conditionsStr = conditionsStr+' AND warehouse_id = :warehouse_id'
      end
      conditionsHash[:warehouse_id] = params[:warehouse_id].to_i
    end

    if params[:product_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'product_id = :product_id'
      else
        conditionsStr = conditionsStr+' AND product_id = :product_id'
      end
      conditionsHash[:product_id] = params[:product_id].to_i
    end

    if params[:begin_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date >= :begin_date'
      else
        conditionsStr = conditionsStr+' AND action_date >= :begin_date'
      end
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date <= :end_date'
      else
        conditionsStr = conditionsStr+' AND action_date <= :end_date'
      end
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    count = SeparateOrder.countAllSeparateOrders conditionsStr, conditionsHash

    separateOrders = SeparateOrder.findAllSeparateOrders conditionsStr,conditionsHash,paramsHash
    
    jsonStr="{totalProperty:"+count.to_s+",root:"+separateOrders.to_json(:include=>{:employee=>{:only=>[:id,:name]},:department=>{:only=>[:id,:name]},:auditor=>{:only=>[:id,:name]},:product=>{:only=>[:id,:name]},:warehouse=>{:only=>[:id,:name]}})+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #新增拆分记录，但在审批时才正式拆分数据到结算表
  def create    
    productId = params[:product_id]
    separateOrder = SeparateOrder.new
    separateOrder.company_id = session[:company_id]
    separateOrder.department_id = session[:department_id]
    separateOrder.employee_id = session[:employee_id]
    separateOrder.warehouse_id = params[:warehouse_id]
    separateOrder.description = params[:description]
    separateOrder.quantity = params[:quantity]
    separateOrder.product_id = productId
    separateOrder.action_date = Time.new.strftime("%Y-%m-%d")

    #判断一下当前用户角色是否需求审批
    sysParam =  SysParam.find_by_company_id(session[:company_id])

    #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
    if params[:temporary] == '1'
      separateOrder.deal_with_status = Constants::TEMP_ADD
    else
      if sysParam.audit_for_separate_add == "否"
        separateOrder.auditing_status = Constants::PASS_APPLY_ADD
        separateOrder.deal_with_status = ''
      else
        separateOrder.auditing_status = Constants::AUDIT_APPLY_ADD
      end
    end
    
    
    subProducts = ProductsComponent.all(:conditions=>["product_id = ?",productId])
    subProducts.each do |product|
      separateOrderDetail = SeparateOrderDetail.new
      separateOrderDetail.product_id = product.component_id
      #乘以separateOrder.quantity。
      separateOrderDetail.quantity = product.quantity * separateOrder.quantity
      separateOrder.separate_order_details << separateOrderDetail
    end
    #separateOrder.save!

    #开始事务，确保在流水号正常的情况下，保存入库单时,一但出现问题，则循环执行
    begin
      Sequence.transaction do
        #开始为销售订单取得流水号
        sequence = Sequence.where("company_id = ? AND sub_type = ?",session[:company_id],SeparateOrder.name).first
        sequence.seq_no = sequence.seq_no + 1
        separateOrder.seq_number = sequence.seq_no
        separateOrder.order_number = sequence.ab + ":" + separateOrder.seq_number.to_s + ":" + Date.today.to_s
        sequence.save!
        separateOrder.save!
        #判断一下，如果新增拆分不需要审批，则直接入汇总表
        logger.info params[:temporary]
        logger.info sysParam.audit_for_separate_add
        logger.info (sysParam.audit_for_separate_add == "否")
        if params[:temporary] != '1' && sysParam.audit_for_separate_add == "否"
          #然后正式拆分此拆分单到结算表中。结算的方式就是主表是负数，然后拆分出来的产品是正数。
          productCollection = ProductCollection.new
          productCollection.company_id = separateOrder.company_id
          productCollection.department_id = separateOrder.department_id
          productCollection.employee_id = separateOrder.employee_id
          productCollection.warehouse_id = separateOrder.warehouse_id
          productCollection.action_date = Time.new.strftime("%Y-%m-%d")
          productCollection.product_id = separateOrder.product_id
          productCollection.quantity = 0 - separateOrder.quantity
          productCollection.description =  separateOrder.description
          productCollection.resource_id =  separateOrder.id
          productCollection.resource_type =  SeparateOrder.name
          productCollection.save!
          #以上是减去一个产品，以下是增加拆分后的产品。
          separateOrderDetails = separateOrder.separate_order_details
          separateOrderDetails.each do |separateOrderDetail|
            productCollection = ProductCollection.new
            productCollection.company_id = separateOrder.company_id
            productCollection.department_id = separateOrder.department_id
            productCollection.employee_id = separateOrder.employee_id
            productCollection.warehouse_id = separateOrder.warehouse_id
            productCollection.action_date = Time.new.strftime("%Y-%m-%d")
            productCollection.product_id = separateOrderDetail.product_id
            productCollection.quantity = separateOrderDetail.quantity
            productCollection.description =  separateOrder.description
            productCollection.resource_id =  separateOrder.id
            productCollection.resource_type =  SeparateOrder.name
            productCollection.save!
          end
        end
      end
    rescue ActiveRecord::StaleObjectError
      #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
      #这里特别指序号产生表。
      logger.info "somebody using sn before yours.............................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound................................................................................"
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #编辑拆分记录，但在审批时才正式拆分数据到结算表
  def update
    begin
      separateOrder = SeparateOrder.find(params[:id])
      separateOrder.company_id = session[:company_id]
      separateOrder.department_id = session[:department_id]
      separateOrder.employee_id = session[:employee_id]
      separateOrder.warehouse_id = params[:warehouse_id]
      separateOrder.description = params[:description]
      separateOrder.quantity = params[:quantity]
      separateOrder.product_id = params[:product_id]
      separateOrder.action_date = Time.new.strftime("%Y-%m-%d")

      #判断一下当前用户角色是否需求审批
      sysParam =  SysParam.find_by_company_id(session[:company_id])

      #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
      if params[:temporary] == '1'
        separateOrder.deal_with_status = Constants::TEMP_ADD
      else
        if sysParam.audit_for_separate_add == "否"
          separateOrder.auditing_status = Constants::PASS_APPLY_ADD
          separateOrder.deal_with_status = ''
        else
          separateOrder.auditing_status = Constants::AUDIT_APPLY_ADD
        end
      end

      sysParam =  SysParam.find_by_company_id(session[:company_id])

      #判断一下，如果新增拆分不需要审批，则直接入汇总表
      if params[:temporary] != '1' && sysParam.audit_for_separate_add == "否"
        #先删除以前的记录，此处处理是为了防止sysparams变化引起多余的数据。
        ProductCollection.delete_all("resource_type = 'SeparateOrder' AND resource_id = #{params[:id]}")
        
        #然后正式拆分此拆分单到结算表中。结算的方式就是主表是负数，然后拆分出来的产品是正数。
        productCollection = ProductCollection.new
        productCollection.company_id = separateOrder.company_id
        productCollection.department_id = separateOrder.department_id
        productCollection.employee_id = separateOrder.employee_id
        productCollection.warehouse_id = separateOrder.warehouse_id
        productCollection.action_date = Time.new.strftime("%Y-%m-%d")

        productCollection.product_id = separateOrder.product_id
        productCollection.quantity = 0 - separateOrder.quantity
        productCollection.description =  separateOrder.description
        productCollection.resource_id =  separateOrder.id
        productCollection.resource_type =  SeparateOrder.name
        productCollection.save!
        #以上是减去一个产品，以下是增加拆分后的产品。
        separateOrderDetails = separateOrder.separate_order_details
        separateOrderDetails.each do |separateOrderDetail|
          productCollection = ProductCollection.new
          productCollection.company_id = separateOrder.company_id
          productCollection.department_id = separateOrder.department_id
          productCollection.employee_id = separateOrder.employee_id
          productCollection.warehouse_id = separateOrder.warehouse_id
          productCollection.action_date = Time.new.strftime("%Y-%m-%d")
          productCollection.product_id = separateOrderDetail.product_id
          productCollection.quantity = separateOrderDetail.quantity
          productCollection.description =  separateOrder.description
          productCollection.resource_id =  separateOrder.id
          productCollection.resource_type =  SeparateOrder.name
          productCollection.save!
        end
      end

      separateOrder.save!
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  
  #根据某Id得到拆分记录的详细表信息。
  def getSeparateOrderDetailsById
    separateOrderDetails =  SeparateOrderDetail.where(separate_order_id:params[:separate_order_id])

    jsonStr="{totalProperty:"+separateOrderDetails.length.to_s+",root:"+separateOrderDetails.to_json(:include=>{:product=>{:only=>[:id,:name,:is_suit,:spec,:number]}})+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end


  #根据审批状态得到拆分单。
  def getAllSeparateOrdersByAuditStatus
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = "auditing_status like :auditing_status"
    conditionsHash[:auditing_status] = "%#{Constants::APPLY}%"

    if params[:order_number].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'seq_number in (:order_number)'
      else
        conditionsStr = conditionsStr+' AND seq_number in (:order_number)'
      end

      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:warehouse_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'warehouse_id = :warehouse_id'
      else
        conditionsStr = conditionsStr+' AND warehouse_id = :warehouse_id'
      end
      conditionsHash[:warehouse_id] = params[:warehouse_id].to_i
    end

    if params[:product_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'product_id = :product_id'
      else
        conditionsStr = conditionsStr+' AND product_id = :product_id'
      end
      conditionsHash[:product_id] = params[:product_id].to_i
    end

    if params[:begin_date].to_s != ''

      if conditionsStr == ''

        conditionsStr = 'action_date >= :begin_date'
      else
        conditionsStr = conditionsStr+' AND action_date >= :begin_date'
      end
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date <= :end_date'
      else
        conditionsStr = conditionsStr+' AND action_date <= :end_date'
      end
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    count = SeparateOrder.countAllSeparateOrders conditionsStr, conditionsHash
    separateOrders = SeparateOrder.findAllSeparateOrders conditionsStr,conditionsHash,paramsHash
    jsonStr="{totalProperty:"+count.to_s+",root:"+separateOrders.to_json(:include=>[:employee,:department,:auditor,:product,:warehouse])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #审批拆分产品，并添加到结算表中。
  def updateAuditingStatus
    separateOrder = SeparateOrder.find(params[:separate_order_id])
    info = nil
    if separateOrder !=nil
      auditingStatus = params[:auditing_status]      
      separateOrder.auditor_id = session[:employee_id]
      separateOrder.audit_opinion =  params[:audit_opinion]      
      SeparateOrder.transaction do
        if(auditingStatus == "是")
          auditingStatus ="通过"
          #先删除以前的记录，此处处理是为了防止sysparams变化引起多余的数据。
          ProductCollection.delete_all("resource_type = 'SeparateOrder' AND resource_id = #{params[:separate_order_id]}")
          separateOrder.auditing_status = auditingStatus
          separateOrder.action_date = Time.new.strftime("%Y-%m-%d")
          separateOrder.save
          #然后正式拆分此拆分单到结算表中。结算的方式就是主表是负数，然后拆分出来的产品是正数。
          productCollection = ProductCollection.new
          productCollection.company_id = separateOrder.company_id
          productCollection.department_id = separateOrder.department_id
          productCollection.employee_id = separateOrder.employee_id
          productCollection.warehouse_id = separateOrder.warehouse_id
          productCollection.action_date = Time.new.strftime("%Y-%m-%d")
        
          productCollection.product_id = separateOrder.product_id
          productCollection.quantity = 0 - separateOrder.quantity
          productCollection.description =  separateOrder.description
          productCollection.resource_id =  separateOrder.id
          productCollection.resource_type =  SeparateOrder.name
          productCollection.save!
          #以上是减去一个产品，以下是增加拆分后的产品。
          separateOrderDetails = separateOrder.separate_order_details
          separateOrderDetails.each do |separateOrderDetail|
            productCollection = ProductCollection.new
            productCollection.company_id = separateOrder.company_id
            productCollection.department_id = separateOrder.department_id
            productCollection.employee_id = separateOrder.employee_id
            productCollection.warehouse_id = separateOrder.warehouse_id
            productCollection.action_date = Time.new.strftime("%Y-%m-%d")
            productCollection.product_id = separateOrderDetail.product_id
            productCollection.quantity = separateOrderDetail.quantity
            productCollection.description =  separateOrder.description
            productCollection.resource_id =  separateOrder.id
            productCollection.resource_type =  SeparateOrder.name
            productCollection.save!
          end
        else
          auditingStatus = Constants::REJECT_APPLY_ADD
          separateOrder.auditing_status = auditingStatus
          separateOrder.save!
        end

        #结算表处理完毕。
        info = "成功"
      end
    else
      info = "失败"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #根据某Id得到拆分记录的信息。
  def getSeparateOrderById
    begin
      separateOrder = SeparateOrder.find(params[:id])
      rootStr = separateOrder.to_json(:include=>[:product])
      jsonStr = "{root:["+rootStr+"]}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end


  

  #申请撤消
  def applyToCancel
    begin
      separateOrder = SeparateOrder.find(params[:id])
      sysParam =  SysParam.find_by_company_id(session[:company_id])
      if sysParam.audit_for_separate_cancel == "否"
        separateOrder.auditing_status = Constants::PASS_APPLY_CANCEL
        separateOrder.deal_with_status = Constants::CANCELED
        ProductCollection.delete_all("resource_type = 'SeparateOrder' AND resource_id = #{params[:id]}")
        #如果不需要审批，则把汇总表中的数据设置为is_locked = 1
      else
        separateOrder.auditing_status = Constants::AUDIT_APPLY_CANCEL
      end
      separateOrder.auditor_id = session[:employee_id]
      separateOrder.save!
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
end
